<?php

namespace App\Http\Controllers\Home;

use App\Models\Member;
use App\Models\Order;
use App\Models\Picture;
use App\Models\SaoPay;
use App\Models\Shop;
use App\Models\ShopGoods;
use App\Models\WechatSet;
use App\Models\WxTpl;
use App\Models\XcxTpl;
use App\Support\Printer;


/**
 * 订单控制器
 */
class OrderController extends BaseController
{

    public function __construct(
        Order $order,
        SaoPay $saoPay,
        WechatSet $wechatSet,
        Picture $picture,
        ShopGoods $shopGoods,
        Shop $shop,
        XcxTpl $xcxTpl,
        Member $member,
        WxTpl $wxTpl
    )
    {
        parent::__construct();
        $this->order = $order;
        $this->saoPay = $saoPay;
        $this->wechatSet = $wechatSet;
        $this->picture = $picture;
        $this->shop = $shop;
        $this->shopGoods = $shopGoods;
        $this->xcxTpl = $xcxTpl;
        $this->member = $member;
        $this->wxTpl = $wxTpl;
    }

    public function getIndex()
    {
        $res = $this->order->getMemberOrderList();
        if (!$res) {
            return error($this->order->getError());
        }
        $ajaxData['order_list'] = $res;
        $ajaxData['contact'] = '';
        $shopInfo = $this->shop->_redisGetOneBySid($this->shop_id);
        if ($shopInfo && isset($shopInfo['contact'])) {
            $ajaxData['contact'] = $shopInfo['contact'];
        }
        return success($ajaxData);
    }

    public function getDetail()
    {
        $res = $this->order->getDetail();
        if (!$res) {
            return error('该订单不存在');
        }
        return success($res);
    }

    public function checkShopStatus()
    {
        $shop = $this->shop->_redisGetOneBySid($this->shop_id);
        $msg = '';
        if ($shop['status'] != 1) {
            $msg = '系统维护升级中，暂时无法下单';
        }
        return $msg;
    }

    //线下订单
    public function postAdd()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        if (request('share')) {
            $where['admin_id'] = $this->admin_id;
            $where['buyer_id'] = $this->mid;
            $where['created_at'] = ['>', date('Y-m-d 00:00:00', time() - 1)];
            $flag = $this->order->checkShareOrder($where, request('buyer_address'));

            if (!$flag) {
                return error('您有未完成的订单，勿重复下单');
            }
        }
        $memberInfo = $this->member->getMemberInfoByOpenId($this->xcx_openid, $this->wx_openid, $this->shop_id);
        if (!$memberInfo) {
            return error('非法操作');
        }
        if (!$memberInfo['status']) {
            return error('您已被禁用，无法购买，请联系商家');
        }
        $orderData = $this->order->addOrder();
        if (!$orderData) {
            return error($this->order->getError());
        }
        set_time_limit(0);
        ob_end_clean();
        header("Connection: close");
        header("HTTP/1.1 200 OK");
        header("Content-Type: application/json;charset=utf-8");// 如果前端要的是json则添加，默认是返回的html/text
        ob_start();
        echo json_encode(['status' => 1, 'data' => [], 'msg' => '下单成功']);// 输出结果到前端
        $size = ob_get_length();
        header("Content-Length: $size");
        ob_end_flush();
        flush();
        if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
            fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
        }
        ignore_user_abort(true);// 在关闭连接后，继续运行php脚本
        set_time_limit(0);
        $shopInfo = $this->shop->_redisGetOneBySid($this->shop_id);
        if ($shopInfo['send_mode'] == 1) {
            // 打印订单
            (new Printer())->typeSetting($orderData);
        } else {
            $this->wxTpl->newOrderMsg($orderData, $this->shop_id);
        }
        exit;
    }

    public function postAddBillOrder()
    {
//        if ($msg = $this->checkShopStatus()) {
//            return error($msg);
//        }
        if (request('share')) {
            $where['admin_id'] = $this->admin_id;
            $where['buyer_id'] = $this->mid;
            $where['created_at'] = ['>', date('Y-m-d 00:00:00', time() - 1)];
            $flag = $this->order->checkShareOrder($where, request('buyer_address'));

            if (!$flag) {
                return error('您有未完成的订单，勿重复下单');
            }
        }

        $memberInfo = $this->member->getMemberInfoByOpenId($this->xcx_openid, $this->wx_openid, $this->shop_id);
        if (!$memberInfo) {
            return error('非法操作');
        }
        if (!$memberInfo['status']) {
            return error('您已被禁用，无法购买，请联系商家');
        }
        $orderData = $this->order->addBillOrder();
        if (!$orderData) {
            return error($this->order->getError());
        }
        set_time_limit(0);
        ob_end_clean();
        header("Connection: close");
        header("HTTP/1.1 200 OK");
        header("Content-Type: application/json;charset=utf-8");// 如果前端要的是json则添加，默认是返回的html/text
        ob_start();
        echo json_encode(['status' => 1, 'data' => [], 'msg' => '下单成功']);// 输出结果到前端
        $size = ob_get_length();
        header("Content-Length: $size");
        ob_end_flush();
        flush();
        if (function_exists("fastcgi_finish_request")) { // yii或yaf默认不会立即输出，加上此句即可（前提是用的fpm）
            fastcgi_finish_request(); // 响应完成, 立即返回到前端,关闭连接
        }
        ignore_user_abort(true);// 在关闭连接后，继续运行php脚本
        set_time_limit(0);
        $shopInfo = $this->shop->_redisGetOneBySid($this->shop_id);
        if ($shopInfo['send_mode'] == 1) {
            // 打印订单
            (new Printer())->typeSetting($orderData);
        } else {
            $this->wxTpl->newOrderMsg($orderData, $this->shop_id);
        }
        exit;
    }

    public function getDelete()
    {
        $res = $this->order->delete();
        if (!$res) {
            return error($this->order->getError());
        }
        return success($res);
    }

    /**
     * 线上订单预支付请求接口(POST)
     * $orderId        order_id
     * $openid         openid
     * $body      商品简单描述
     * $order_sn    订单编号
     * $total_fee   金额
     * json的数据
     */
    public function postPay()
    {
        if ($msg = $this->checkShopStatus()) {
            return error($msg);
        }
        $memberInfo = $this->member->getMemberInfoByOpenId($this->xcx_openid, $this->wx_openid, $this->shop_id);
        if (!$memberInfo) {
            return error('非法操作');
        }
        if (!$memberInfo['status']) {
            return error('您已被禁用，无法购买，请联系商家');
        }
        $orderId = intval(request('order_id', 0));
        if (!$orderId) {
            $order = $this->order->addOrder();
            if (!$order || empty($order)) {
                return error($this->order->getError());
            }
        } else {
            $where['id'] = $orderId;
            $order = $this->order->_getOne($where);
            if (!$order || $order['status'] != 10) {
                return error('支付异常');
            }
        }
        $openid = request('openid');
        $result = $this->saoPay->prepay($this->xcx_openid, $this->wx_openid, $order, $openid);
        if (!$result) {
            return error($this->saoPay->getError() ? $this->saoPay->getError() : '未知错误');
        }
        $result['id'] = $order['id'];
        return success($result);
    }

    /**
     * 支付回调
     * 返回数组去修改支付订单数据
     */
    public function anyPayNotify()
    {
        $this->saoPay->notify(1);
    }

    public function getCheckStatus()
    {
        $orderId = request('id');
        if (!$orderId) {
            return error('非法操作');
        }
        $res = $this->order->_getOne(['id' => $orderId]);
        if (!$res) {
            return error('该订单不存在');
        }
        $ajax['result'] = $res['status'] == 20 ? true : false;
        return success($ajax);
    }

}
